import fix_path
import os

from functools import wraps
from interessa_fb import BaseHandler
from interessa_fb import FB_User as FBUser
from model import *

from google.appengine.ext import webapp
from google.appengine.ext.webapp import util


def user_required(fn):
    """Decorator to ensure a user is present"""
    @wraps(fn)
    def wrapper(*args, **kwargs):
        handler = args[0]
        if handler.user:
            return fn(*args, **kwargs)
        handler.redirect(u'/')
    return wrapper


class WelcomeHandler(BaseHandler):
    """Show application frontpage information""" #ToDo Insert commitment design! 
    def get(self):
        self.render(u'welcome')

class UserHandler(BaseHandler):
    """Show specific user's informations"""
    @user_required
    def get(self, user_id):
        if self.user.user_id == user_id:
            fb_user = FBUser.get_by_key_name(user_id)
            if not fb_user:
                self.set_message(type=u'error',
                    content=u'Este usuario ainda nao utiliza o Interessa!')
                self.redirect(u'/')
                return
            #Let's connect FBUser and Interessa models
            user_id="FB_"+fb_user.user_id #ToDo - do it right MAN!
            i_users = User.find_by_id(user_id)
            if len(i_users)==0:
                #create
		i_user=User(user_id=user_id,name=fb_user.name)
                i_user.put()
            else:
                i_user=i_users[0]
            #Now you can render page
            self.render(u'user',
                user=fb_user,
                topics=i_user.all_topics(),
            )
        else:
            self.set_message(type=u'error',
                content=u'You are not allowed to see that.')
            self.redirect(u'/')

class AddTopicHandler(BaseHandler):
    """Adds a new topic of user's interest."""
    @user_required
    def post(self):
        user_id=self.user.user_id
        fb_user = FBUser.get_by_key_name(user_id)
        if not fb_user:
            self.set_message(type=u'error',
                content=u'Este usuario ainda nao utiliza o Interessa!')
            self.redirect(u'/')
            return
        i_users = User.find_by_id("FB_"+user_id)
        if len(i_users)==0:
            self.set_message(type=u'error',content=u'You are not allowed to see that.')
            self.redirect(u'/')
        else:
            i_user = i_users[0]
            i_user.add_topic(self.request.POST[u'topic'].strip())
            self.render(u'user',user=fb_user,topics=i_user.topics)    

def main():
    routes = [
        (r'/', WelcomeHandler),
        (r'/user/(.*)', UserHandler),
        (r'/addTopic', AddTopicHandler),
    ]
    application = webapp.WSGIApplication(routes,debug=os.environ.get('SERVER_SOFTWARE', '').startswith('Dev'))
    util.run_wsgi_app(application)


if __name__ == u'__main__':
    main()

